import 'package:flutter/material.dart';

//分类 model层
import '../../model/CateModel.dart';

//动态设置宽高比
import '../../services/ScreenAdapter.dart';

//网络请求层
import '../../config/Config.dart';
import 'package:dio/dio.dart';

class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage>
    with AutomaticKeepAliveClientMixin {
  @override
  //保持页面持久化
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._getLeftCateData();
  }

  //当前默认选中的分类
  int _selectIndex = 0;

  //请求api里的左侧分类数据  start
  List _leftCateList = [];
  _getLeftCateData() async {
    var api = "${Config.domain}api/pcate";
    var result = await Dio().get(api);
    var leftCateList = new CateModel.fromJson(result.data);
    setState(() {
      this._leftCateList = leftCateList.result;
    });

    //初始化时 同步请求下对应的右侧分类商品数据，就是第一页的数据
    this._getRightCateData(this._leftCateList[0].sId);
  }

  Widget _leftCateWidget(leftWidth) {
    if (_leftCateList.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity, //自适应高度
        color: Colors.white,
        child: ListView.builder(
          itemCount: this._leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: [
                Divider(
                  height: 1,
                ),
                InkWell(
                  onTap: () {
                    setState(() {
                      _selectIndex = index;

                      //点击分类时自动获取对应的分类商品数据
                      this._getRightCateData(_leftCateList[index].sId);
                    });
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenAdapter.height(80),
                    padding: EdgeInsets.only(top: ScreenAdapter.height(24)),
                    color: this._selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                    child: Text(
                      '${this._leftCateList[index].title}',
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
                Divider(
                  height: 1,
                ),
              ],
            );
          },
        ),
      );
    } else {
      return Container(
        width: leftWidth,
        height: double.infinity, //自适应高度
        color: Colors.white,
        child: Text('加载中'),
      );
    }
  }
  //请求api里的左侧分类数据 end

  //右侧数据 start
  List _rightCateList = [];
  _getRightCateData(pid) async {
    //拼装请求链接
    var api = "${Config.domain}api/pcate?pid=${pid}";
    var result = await Dio().get(api);
    var leftCateList = CateModel.fromJson(result.data);
    setState(() {
      this._rightCateList = leftCateList.result;
    });
  }

  Widget _rightCateWidget(rightItemWidth, rightItemHeight) {
    if (this._rightCateList.length > 0) {
      return Expanded(
        //自适应布局
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          child: GridView.builder(
            //设置GridView的边距和数量等
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: rightItemWidth / rightItemHeight, //高宽比例
                // childAspectRatio:1/1.2,//要一个长方形效果 上面是图片 下面是text文字
                crossAxisSpacing: 8, //左右边距
                mainAxisSpacing: 8 //下方边距
                ),

            itemCount: this._rightCateList.length, //设置数量
            itemBuilder: (context, index) {
              //处理图片
              String pic = this._rightCateList[index].pic;
              pic = Config.domain + pic.replaceAll('\\', '/');

              return InkWell(
                onTap: () {
                  // print('正在点击商品信息 当前商品id为 ${_rightCateList[index].sId}');

                  //点击商品信息时，跳转到对应的商品分类页面
                  Navigator.pushNamed(context, '/productList', arguments: {
                    "cid": this._rightCateList[index].sId,
                  });
                },
                child: Container(
                  child: Column(
                    children: <Widget>[
                      AspectRatio(
                        aspectRatio: 1 / 1,
                        child: Image.network(
                          pic,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Container(
                        height: ScreenAdapter.height(32),
                        child: Text('${this._rightCateList[index].title}'),
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      );
    } else {
      return Expanded(
          //自适应布局
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: Text(' 数据加载中'),
          ));
    }
  }
  //右侧数据 end

  @override
  Widget build(BuildContext context) {
    //配合ScreenAdapter取宽高
    ScreenAdapter.init(context);

    //设置当前左侧分类的宽，设置为跟整个屏幕的四分之一
    var leftWidth = ScreenAdapter.getScreenWidth() / 4;

    //获取右项 每一侧的宽度= （总宽度 - 左侧分类宽度 - GridView外侧元素左右的Padding值）/3 因为放3个
    var rightItemWidth =
        (ScreenAdapter.getScreenWidth() - (leftWidth - 20 - 20)) / 3;
    rightItemWidth = ScreenAdapter.width(rightItemWidth); //获取右侧的宽度

    //获取右项高度  每一侧的高度等于 每个的宽度 + text容器的高度  (因为图片的是正方形的)
    var rightItemHeight = rightItemWidth + ScreenAdapter.height(28);

    //设置ScreeAdaper时必须得在build里引入
    return Row(
      children: [
        //左项分类数据
        this._leftCateWidget(leftWidth),

        //右项分类数据
        this._rightCateWidget(rightItemWidth, rightItemHeight),
      ],
    );
  }
}
